﻿#include "RobotServer.h"

#define SOCKBUF_SIZE (67108864)  //(1024*1024*64)
#define SOCKBUF_SIZE_THRESH (62914560)  //(1024*1024*60)


RobotServer::RobotServer(quint16 usPort, QObject *parent)
    : QObject(parent)
{
    m_socketCur = nullptr;
    m_server = new QTcpServer(this);
    m_server->listen(QHostAddress::Any, usPort);
    connect(m_server, &QTcpServer::newConnection, this, &RobotServer::onNewConnection);

    m_llRecvBegin = 0;
    m_llRecvEnd = 0;
    m_buf = new char[SOCKBUF_SIZE];
}

RobotServer::~RobotServer()
{
}

void RobotServer::onNewConnection()
{
    if (nullptr != m_socketCur)
    {
        disconnect(m_socketCur);
        m_socketCur->deleteLater();
        m_socketCur = nullptr;
    }

    while (m_server->hasPendingConnections())
    {
        qDebug() << "new connection, port: " << m_server->serverPort();
        m_socketCur = m_server->nextPendingConnection();
        connect(m_socketCur, &QTcpSocket::readyRead, this, &RobotServer::onSocketReadReady);
        connect(m_socketCur, &QTcpSocket::stateChanged, this, &RobotServer::onSockStateChanged);
    }
}

void RobotServer::onSocketReadReady()
{
    if (nullptr == m_socketCur)
    {
        return;
    }

    qDebug() << "new data from" << m_socketCur->peerPort();

    if (m_llRecvEnd > SOCKBUF_SIZE_THRESH)
    {
        memmove(m_buf, m_buf+m_llRecvBegin, m_llRecvEnd-m_llRecvBegin);
        m_llRecvEnd -= m_llRecvBegin;
        m_llRecvBegin = 0;
    }

    qint64 llRead = m_socketCur->read(m_buf+m_llRecvEnd, SOCKBUF_SIZE-m_llRecvEnd);
    m_llRecvEnd += llRead;
    int nParsed = parse((unsigned char*)m_buf+m_llRecvBegin, m_llRecvEnd-m_llRecvBegin);
    m_llRecvBegin += nParsed;
}

void RobotServer::onSockStateChanged(QAbstractSocket::SocketState s)
{
    if (QAbstractSocket::UnconnectedState == s)
    {
        qDebug() << "socket disconnected, port: " << m_server->serverPort();
        disconnect(m_socketCur, &QTcpSocket::readyRead, this, &RobotServer::onSocketReadReady);
        disconnect(m_socketCur, &QTcpSocket::stateChanged, this, &RobotServer::onSockStateChanged);
        m_socketCur->deleteLater();
        m_socketCur = nullptr;
    }
}

int RobotServer::parse(unsigned char *buff, qint64 len)
{
    return 0;
}
